<template>
  <div class="confirm">
    <Header title="确认订单"></Header>

    <!-- 地址选择 -->
    <AddressSelect
      :selectedAddress="deliveryAddress.selectedAddress"
      @selectAddress="visibleStatus.addressSelectDialog = true"
    />
    <nut-address
      v-model:visible="visibleStatus.addressSelectDialog"
      type="exist"
      :exist-address="deliveryAddress.list"
      :is-show-custom-address="false"
      @selected="handleSelectedAddress"
      exist-address-title="配送至"
    ></nut-address>

    <!-- 订单信息 -->
    <div class="orderInfoBox"> 
      <OrderItem
        v-for="(orderItem, orderItemIndex) in confirmData.orderItemList"
        :key="orderItemIndex"
        :orderItem="orderItem"
      />
    </div>

    <!-- 金额信息 -->
    <div class="amountBox">
      <AmountItem title="商品金额" :amount="confirmData.productAmount" />
      <AmountItem
        title="运费"
        :amount="confirmData.deliveryAmount"
        symbol="+"
      />
      <AmountItem
        title="优惠"
        :amount="confirmData.discountAmount"
        symbol="-"
      />
      <AmountItem title="合计" :amount="confirmData.payAmount" />
    </div>

    <!-- 支付方式 -->
    <nut-popup
      position="bottom"
      closeable
      round
      v-model:visible="visibleStatus.paySelectDialog"
    >
      <div class="paySelectBox">
        <PaySelect
          :confirmData="confirmData"
          :loading="loadingStatus.pay"
          @pay="payOrder"
        />
      </div>
    </nut-popup>

    <ConfirmBottom
      :confirmData="confirmData"
      :hasSubmit="orderData.hasSubmit"
      @submit="submitOrder"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const { proxy } = getCurrentInstance();

import AmountItem from "./components/AmountItem.vue";
import AddressSelect from "./components/AddressSelect.vue";
import PaySelect from "./components/PaySelect.vue";
import ConfirmBottom from "./components/ConfirmBottom.vue";

// 重复提交token
const repeatSubmitToken = ref(null);
const getRepeatSubmitToken = () => {
  proxy.$thirdApi.common
    .repeatSubmitToken()
    .then((res) => {
      repeatSubmitToken.value = res.data;
    })
    .catch((error) => {});
};

// 可见状态管理
const visibleStatus = reactive({
  addressSelectDialog: false,
  paySelectDialog: false,
});

// 按钮状态管理
const loadingStatus = reactive({
  submit: false,
  pay: false,
});

// 商品列表和金额信息
const orderData = reactive({
  hasSubmit: false,
  orderId: null,
});
const confirmData = reactive({});

// 初始化路由参数
const routeParams = reactive({
  cartMode: false,
  cartIds: [],
  addressId: null,
  skuQuantityList: [],
});
const initRouterParams = () => {
  routeParams.cartMode = history.state.cartMode;
  routeParams.cartIds = history.state.cartIds;
  routeParams.addressId = history.state.addressId;
  routeParams.skuQuantityList = history.state.skuQuantityList;
};

// 收货地址列表
const deliveryAddress = reactive({
  selectedAddress: {},
  list: [],
});
// 选中收货地址事件
const handleSelectedAddress = (prevSelected, nowSelected, arr) => {
  deliveryAddress.selectedAddress = nowSelected;
};
// 收货地址
const remoteAddressList = () => {
  proxy.$memberApi.address.list(proxy.$userUtils.getUserId()).then((res) => {
    // 已有地址参数，选中匹配地址
    res.data.forEach((item) => {
      item.countyName = item.countryName;
      item.townName = "";
      if (routeParams.addressId == item.id) {
        handleSelectedAddress(null, item, null);
        item.selectedAddress = true;
      } else {
        item.selectedAddress = false;
      }
    });

    // 没有地址参数，选中默认地址
    res.data.forEach((item) => {
      item.countyName = item.countryName;
      item.townName = "";
      if (
        proxy.$arrayUtils.isEmptyObj(deliveryAddress.selectedAddress) &&
        item.defaultAddressFlag
      ) {
        handleSelectedAddress(null, item, null);
        item.selectedAddress = true;
      }
    });
    deliveryAddress.list = res.data;
  });
};

// 获取商品金额信息
const remoteConfirmResult = () => {
  proxy.$orderApi.order
    .confirm(routeParams.addressId, routeParams.skuQuantityList)
    .then((res) => {
      Object.assign(confirmData, res.data);
    });
};

// 支付
const payOrder = (type) => {
  if (type == "2") {
    proxy.$orderApi.order
      .aliMobileWapPay(
        orderData.orderId,
        encodeURIComponent(
          "http://" + window.location.host + "/#/order/pay/success"
        )
      )
      .then((res) => {
        document.write(res.data);
      })
      .catch((error) => {});
  } else {
    proxy.$showToast.fail("该支付方式正在对接中");
  }
};

const stockNotEnough = reactive({
  list: [],
});

// 提交订单
const submitOrder = () => {
  // TODO 提交订单后又重新修改了地址
  if (orderData.hasSubmit) {
    visibleStatus.paySelectDialog = true;
    return;
  }

  if (null == deliveryAddress.selectedAddress.id) {
    proxy.$showToast.fail("请选择收货地址");
    return;
  }

  loadingStatus.submit = true;
  proxy.$orderApi.order
    .submit({
      repeatSubmitToken: repeatSubmitToken.value,
      cartMode: routeParams.cartMode,
      cartIds: routeParams.cartIds,
      memberId: proxy.$userUtils.getUserId(),
      addressId: deliveryAddress.selectedAddress.id,
      skuQuantityList: routeParams.skuQuantityList,
    })
    .then((res) => {
      orderData.hasSubmit = true;
      orderData.orderId = res.data;
      visibleStatus.paySelectDialog = true;

      // 删除购物车
      if (routeParams.cartMode) {
        proxy.$cartApi.cart.deleteCart(routeParams.cartIds).then((res) => {
          proxy.$cartUtils.refreshCartList();
        });
      }
    })
    .catch((error) => {
      // 库存不足
      if (error.data && error.data.data.length > 0) {
        stockNotEnough.list = error.data.data;
      }
      loadingStatus.submit = false;
    });
};

// 页面加载完成
onMounted(() => {
  getRepeatSubmitToken();
  initRouterParams();
  remoteAddressList();
  remoteConfirmResult();
});
</script>

<style lang="less" scoped>
.confirm {
  .paySelectBox {
    padding: 30px 25px;
  }
  :deep(.nut-address__header__title) {
    font-size: 14px;
  }
  .orderInfoBox {
    margin: 5px 5px 0px 5px;
    padding: 10px;
    border-radius: 5px;
    background: #fff;
  }
  .amountBox {
    margin: 5px 5px 0px 5px;
    padding: 10px;
    border-radius: 5px;
    background: #fff;
  }
  :deep(.nut-address__header) {
    height: 50px;
  }
  :deep(.nut-address__exist) {
    margin-top: 0px;
    .nut-address__exist-group {
      height: auto;
      padding: 0px 20px 20px 20px;
    }
  }
  :deep(.nut-address__exist-item-info) {
    .nut-address__exist-item-info-name {
      margin-bottom: 5px;
    }
    .nut-address__exist-item-info-phone {
      margin-bottom: 5px;
    }
  }
}
</style>